package org.example.type1;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 插入 Markdown 标记
 * cmd 调用命令格式：
 * java MarkdownInsert title 1 ：插入 Markdown 1级标题 #
 * java MarkdownInsert title 2 ：插入 Markdown 2级标题 ##
 * java MarkdownInsert title 3 ：插入 Markdown 3级标题 ###
 * java MarkdownInsert timeStamp ：插入时间戳，如 2024-01-23 10:23:50
 * java MarkdownInsert horizontalLine ：插入水平线 ***
 * java MarkdownInsert col_to_in_fun ：行转列，转为 in 函数参数值，如 'a','b','c'
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2021/1/6 17:13
 */
@SuppressWarnings("all")
public class MarkdownInsert {

    public static void main(String[] args) {
        String insertData = "";
        if (args == null || args.length == 0) {
            writeLog("Error：Parameter cannot be empty！");
            return;
        }
        String type = args[0];
        if (type.equals("timeStamp")) {
            //插入时间戳
            Date nowDate = new Date();
            insertData = String.format("%1$tF %1$tT", nowDate);
        } else if (type.equals("title") && args.length == 2) {
            //插入标题
            String level = args[1];
            for (int i = 0; i < Integer.parseInt(level); i++) {
                insertData += "#";
            }
            insertData = insertData + "  " + insertData;
        } else if (type.equals("horizontalLine")) {
            insertData = "***";
        } else if (type.equals("col_to_in_fun")) {
            // 每一行的数据使用逗号链接起来，用于生成 in 函数参数，如 'a','b','c'
            String text = readClipboardData();
            String[] split = text.split("\n");
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                if (split[i] == null || "".equals(split[i].trim())) {
                    continue;
                }
                sBuilder.append("'").append(split[i]).append("'");
                if (i < split.length - 1) {
                    sBuilder.append(",");
                }
            }
            insertData = sBuilder.toString();
        }
        // 按下 alt + tab 健，将 cmd 窗口切换到下一层
        pressCtrlAndSingleKeyByNumber(KeyEvent.VK_ALT, KeyEvent.VK_TAB);
        writeLog("Press the alt+tab keys to switch the cmd window to the next layer");
        try {
            //延迟 300 毫秒，等待上面切换窗口得动作
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            writeLog("InterruptedException failed：" + e.getMessage());
        }
        // 创建字符串选择器，并将内容传给它
        StringSelection stringSelection = new StringSelection(insertData);
        // 创建系统剪贴板，并设置内容
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);

        // 最后按 Ctrl + v 快捷键，将系统剪切板中得内容粘贴出来.
        writeLog("Press Ctrl+v shortcut key to paste the content from the system clipboard.");
        pressCtrlAndSingleKeyByNumber(KeyEvent.VK_CONTROL, KeyEvent.VK_V);
    }

    /**
     * 模拟按下键盘快捷键，比如文档起始位置：Ctrl+Home，结束位置：Ctrl+End、复制 Ctrl + C、粘贴 Ctrl + V
     *
     * @param firstKeyCode ：第一个按键的值,如 Ctrl键是：KeyEvent.VK_CONTROL、alt 健是 KeyEvent.VK_ALT
     * @param keycode      ：第二个按键的值,如End键:KeyEvent.VK_END、Home键：KeyEvent.VK_HOME、V健：KeyEvent.VK_V
     */
    public static void pressCtrlAndSingleKeyByNumber(int firstKeyCode, int keycode) {
        try {
            Robot robot = new Robot();
            robot.keyPress(firstKeyCode);
            robot.keyPress(keycode);
            robot.keyRelease(keycode);
            robot.keyRelease(firstKeyCode);
            robot.delay(100);
        } catch (AWTException e) {
            writeLog("pressCtrlAndSingleKeyByNumber failed：" + e.getMessage());
        }
    }

    /**
     * 读取系统剪切板文本内容
     *
     * @throws Exception
     */
    public static String readClipboardData() {
        String text = "";
        try {
            // 创建 Clipboard 对象
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            // 从剪贴板获取内容
            Transferable transferable = clipboard.getContents(null);
            // 判断内容类型
            if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                text = (String) transferable.getTransferData(DataFlavor.stringFlavor);
                writeLog("read clipboard text content：" + text);
            } else {
                text = "Invalid or unsupported clipboard text content";
                writeLog("Invalid or unsupported clipboard text content");
            }
        } catch (Exception e) {
            writeLog("Reading system clipboard text content failed：" + e.getMessage());
            text = "Reading system clipboard text content failed";
        }
        return text;
    }

    /**
     * 使用 FileWriter 文件字符输出流写入文件
     *
     * @param text     ：被写入的内容
     * @param destFile ：被写入的文件
     * @param append   ：是否追加内容
     */
    public static void writeLog(String text) {
        boolean append = true;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = sdf.format(new Date());
        File destFile = new File("./logs/MarkdownInsert_info.log");
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
            try {
                Files.createFile(destFile.toPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(destFile, append);
            fileWriter.append("[" + dateTime + "] [info] - " + text + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileWriter != null) {
                    fileWriter.flush();
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
